'use strict';

const db = uniCloud.database();
const periodCollection = db.collection('period_records');

exports.main = async (event, context) => {
	// 获取用户ID和日期
	const { userId, date, symptoms = [], flowLevel = 1, notes = '' } = event;
	
	if (!userId || !date) {
		return {
			code: 1,
			message: '缺少必要参数'
		}
	}
	
	try {
		// 解析日期，确保正确处理本地时区
		const dateParts = date.split('-');
		if (dateParts.length !== 3) {
			return {
				code: 2,
				message: '日期格式错误，应为YYYY-MM-DD'
			}
		}
		
		// 解析年月日
		const year = parseInt(dateParts[0]);
		const month = parseInt(dateParts[1]) - 1; // JS月份从0开始
		const day = parseInt(dateParts[2]);
		
		// 防止时区偏移，创建日期时直接使用UTC时间
		const recordDate = new Date(Date.UTC(year, month, day, 0, 0, 0));
		
		// 检查该日期是否已经有记录
		const existRecord = await periodCollection.where({
			user_id: userId,
			date: recordDate
		}).limit(1).get();
		
		// 如果已存在记录，返回成功（不重复添加）
		if (existRecord.data && existRecord.data.length > 0) {
			return {
				code: 0,
				message: '该日期已存在月经记录',
				data: existRecord.data[0]
			}
		}
		
		// 添加新记录
		const result = await periodCollection.add({
			user_id: userId,
			date: recordDate,
			symptoms,
			flow_level: flowLevel,
			notes
		});
		
		return {
			code: 0,
			message: '添加月经记录成功',
			data: {
				_id: result.id,
				userId,
				date: recordDate,
				symptoms,
				flowLevel,
				notes
			}
		}
	} catch (error) {
		console.error('添加月经记录失败:', error);
		return {
			code: 500,
			message: '添加月经记录失败:' + error.message
		}
	}
}; 